﻿using System;
using System.Data;
using System.Drawing;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dundas.Charting.WebControl;
using System.IO;
using LenderClearingHouse.Helpers;

namespace LenderClearingHouse
{
    public partial class Dashboard : PageBase
    {
        private const int StartRowIndex = 0;
        private const int pageSize = 10;
        //private const string barWidth = "0.6";
        String ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        protected void Page_Load(object sender, System.EventArgs e)
        {

            String filter = String.Empty;
            if (!String.IsNullOrEmpty(Request.QueryString["c"]))
            {
                filter = Request.QueryString["c"];
            }
            ViewState["filter"] = filter;

            var listDate = DateValidator.ValidateCalendarDate(txtFromDate.Text, txtToDate.Text, CalendarFromDate.SelectedDate, CalendarToDate.SelectedDate);
            txtFromDate.Text = listDate.ElementAt(0).ToString();
            txtToDate.Text = listDate.ElementAt(1).ToString();
            CalendarFromDate.SelectedDate = Convert.ToDateTime(listDate.ElementAt(2));
            CalendarToDate.SelectedDate = Convert.ToDateTime(listDate.ElementAt(3));

            pagerBottom.Visible = true;
            pagerTop.Visible = true;
            pagerTop.PageSize = pageSize;
            pagerBottom.PageSize = pageSize;

            for (int i = 0; i <= 3; ++i)
            {
                Chart1.Series[i].Type = SeriesChartType.Column;
                /*Chart1.Series[i].EmptyPointStyle.BorderWidth = 0;
                Chart1.Series[i].EmptyPointStyle.MarkerStyle = MarkerStyle.None;*/
            }

            Chart1.Titles.Add("Estimate vs Actual", Docking.Top, new Font("Arial", 18), ColorTranslator.FromHtml("#000000"));

            Chart1.Series[0].Color = ColorTranslator.FromHtml("#93c572");
            Chart1.Series[1].Color = Color.Red;
            Chart1.Series[2].Color = ColorTranslator.FromHtml("#3ca9d0");
            Chart1.Series[3].Color = Color.Yellow;

            Chart1.ChartAreas[0].AxisX.Interval = 1;
            Chart1.ChartAreas[0].AxisX.LabelStyle.ShowEndLabels = false;

            Chart1.ChartAreas["Default"].AxisY.Title = "$ (Dollars)";
            Chart1.ChartAreas["Default"].AxisY.TitleFont = new Font("Microsoft Sans Serif", 15);

            if (!this.Page.IsPostBack)
            {
                // Set initial X axis zooming
                //this.Chart1.ChartAreas["Default"].AxisX.View.Position = -1;
                //this.Chart1.ChartAreas["Default"].AxisX.View.Size = pageSize + 1.5;

                FillChart(0, filter);
                cbInvestor.Visible = lbIvestor.Visible;
            }

            AddFilter(pnlABC1, filter);
            AddFilter(pnlABC2, filter);
        }

        private void AddFilter(Panel pnl, String filter)
        {
            foreach (var chr in ABC)
            {
                HyperLink h = new HyperLink();
                h.Text = chr.ToString();
                h.NavigateUrl = "~/Dashboard.aspx?c=" + chr;
                if (filter.ToUpper() == chr.ToString().ToUpper())
                {
                    h.CssClass = "selectedFilter";
                }
                else 
                {
                    h.CssClass = "notSelectedFilter";
                }
                pnl.Controls.Add(h);
            }

            HyperLink hAll = new HyperLink();
            hAll.Text = "All";
            hAll.NavigateUrl = "~/Dashboard.aspx";
            if (String.IsNullOrEmpty(filter))
            {
                hAll.CssClass = "selectedFilter";
            }
            else 
            {
                hAll.CssClass = "notSelectedFilter";
            }
            pnl.Controls.Add(hAll);
        }

        private void FillChart(int startRow, String filter = "")
        {
            User u = Session["User"] as User;

            DateTime fromDate = CalendarFromDate.SelectedDate.HasValue ? CalendarFromDate.SelectedDate.Value : DateTime.Now;
            DateTime toDate = CalendarToDate.SelectedDate.HasValue ? CalendarToDate.SelectedDate.Value : DateTime.Now; 

            int investorId = -1;
            if (u.UserRole == UserRole.SuperAdmin)
            {
                investorId = cbInvestor.SelectedIndex != -1 ? int.Parse(cbInvestor.SelectedValue) : -1;
            }
            else
            {
                investorId = int.Parse(u.UserId);
            }
             
            DataAccess da = new DataAccess();
            DataTable tbl;

            if ((u.UserRole == UserRole.InvestorUser) || (u.UserRole == UserRole.InvestorAdmin))
                tbl = da.GetDataTable("getDashboard1", new string[] { "@InvestorId", "@fromDate", "@toDate" }, new object[] { u.UserId, fromDate, toDate });
            else if (u.UserRole == UserRole.SuperAdmin)
            {
                tbl = investorId > 0 ? da.GetDataTable("getDashboard1", new string[] { "@InvestorId", "@fromDate", "@toDate" }, new object[] { investorId, fromDate, toDate })
                    : da.GetDataTable("getDashboard1", new string[] { "@fromDate", "@toDate" }, new object[] { fromDate, toDate }); 
            }  
            else
            {
                SetNoAccess();
                return;
            }

            tbl = FilterDataTable(tbl, filter);

            for (int i = 0; i < tbl.Rows.Count % pageSize; ++i)
            {
                tbl.Rows.Add(tbl.NewRow());
                tbl.AcceptChanges();
            }

            for (int i = startRow; i < Math.Min(startRow + pageSize, tbl.Rows.Count); ++i)
            {
                DataRow dr = tbl.Rows[i];

                int j = i - startRow;
                if (dr.IsNull("PropertyLocation"))
                {
                    Chart1.Series[0].Points.AddXY(j, double.NaN);
                    Chart1.Series[1].Points.AddXY(j, double.NaN);
                    Chart1.Series[2].Points.AddXY(j, double.NaN);
                    Chart1.Series[3].Points.AddXY(j, double.NaN);

                    Chart1.Series[0].Points[j].AxisLabel = " ";
                    Chart1.Series[1].Points[j].AxisLabel = " ";
                    Chart1.Series[2].Points[j].AxisLabel = " ";
                    Chart1.Series[3].Points[j].AxisLabel = " ";
                }
                else
                {
                    Chart1.Series[0].Points.AddXY(j, Convert.ToInt32(dr["EstimatedResale"]));
                    Chart1.Series[1].Points.AddXY(j, Convert.ToInt32(dr["ActualResale"]));
                    Chart1.Series[2].Points.AddXY(j, Convert.ToInt32(dr["EstimatedRehab"]));
                    Chart1.Series[3].Points.AddXY(j, Convert.ToInt32(dr["ActualRehab"]));

                    Chart1.Series[0].Points[j].AxisLabel = dr["PropertyLocation"].ToString();
                    Chart1.Series[1].Points[j].AxisLabel = dr["PropertyLocation"].ToString();
                    Chart1.Series[2].Points[j].AxisLabel = dr["PropertyLocation"].ToString();
                    Chart1.Series[3].Points[j].AxisLabel = dr["PropertyLocation"].ToString();
                }
            }

            if (tbl.Rows.Count < 1)
            {
                pagerBottom.Visible = false;
                pagerTop.Visible = false;
            }

            lvFake.DataSource = tbl;
            lvFake.DataBind();
        }

        private DataTable FilterDataTable(DataTable tbl, string filter)
        {
            if (tbl.Rows.Count == 0)
                return tbl;

            if (!String.IsNullOrEmpty(filter))
            {
                var list = tbl.AsEnumerable().Where(r => r.Field<String>(1).Split(' ')[1].Substring(0, 1).ToUpper() == filter.ToUpper())
                                             .OrderBy(f => f.Field<String>(1).Split(' ')[1].Substring(0))
                                             .ToList();

                if (list.Count > 0)
                {
                    DataTable newTable = list.CopyToDataTable();
                    return newTable;
                }
                else
                {
                    pnlNoItems.Visible = true;
                    return new DataTable();
                }
            }
            else 
            {
                var list = tbl.AsEnumerable().OrderBy(f => f.Field<String>(1).Split(' ')[1].Substring(0)).ToList();
                DataTable newTable = list.CopyToDataTable();
                return newTable;
            }
            
        }



        protected void lvFake_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
        {
            //set current page startindex, max rows and rebind to false
            pagerBottom.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
            pagerTop.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);

            String filter = ViewState["filter"] as String;
            //rebind List View
            FillChart(e.StartRowIndex, filter);
        }

        private void SetNoAccess()
        {
            Chart1.Visible = false;
            pagerBottom.Visible = false;  
            pagerTop.Visible = false;
            
        }

        /*public void Chart_PrePaint(object sender, Dundas.Charting.WebControl.ChartPaintEventArgs e)
        {
            if (sender is ChartImage)
            {
                for (int i = 0; i < 4; ++i)
                {
                    Chart1.Series[i].DeleteAttribute("PointWidth");
                    Chart1.Series[i]["PointWidth"] = barWidth;
                }
            }
        }*/

        protected void cbInvestor_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            pagerBottom.SetPageProperties(StartRowIndex, pageSize, false);
            pagerTop.SetPageProperties(StartRowIndex, pageSize, false);
            FillChart(StartRowIndex);
        }

        protected void calendarDate_Changed(object sender, System.EventArgs e)
        {
            pagerBottom.SetPageProperties(StartRowIndex, pageSize, false);
            pagerTop.SetPageProperties(StartRowIndex, pageSize, false);
            lblDataValidate.Style.Add("display", "none");
            FillChart(StartRowIndex);
        }
    }
}